package cn.z2huo.knowledge.concurrency.callable.callable;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author z2huo
 */
class FutureTaskTest {

    public static Future<String> getFutureTask(int i) {
        FutureTask<String> stringFutureTask = new FutureTask<>(new MyCallable(i));
        Thread thread = new Thread(stringFutureTask);
        thread.start();
        return stringFutureTask;
    }

    public static void main(String[] args) {

        long start, end;

        List<Future<String>> results = new ArrayList<>();

        start = System.currentTimeMillis();

        for (int i = 0; i < 10; i++) {
            results.add(getFutureTask(i));
        }
        System.out.println("wait result, this is other operate");
        for (Future<String> result : results) {
            try {
                while (!result.isDone()) {
                    TimeUnit.MILLISECONDS.sleep(10);
                }
                System.out.println(result.get());
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        }

        end = System.currentTimeMillis();
        System.out.println("cost time: " + (end - start));

    }
}
